/**
 * @author  weigao<weiga@iflytek.com>
 *
 * @version 1.0.0
 */
package com.iflytek.uoamp.agent.common.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author gaowei
 * 获取性能数据指标;
 */
public class PerDataUtils {

    private static PerDataUtils instance = new PerDataUtils();
    private static Pattern pattern = Pattern.compile("([\\s\\S]*?)=(.*?) ");

    private PerDataUtils(){

    }

    /**
     * 将形如k=v字符串转换成map，同时会过滤key和value两边的空格；
     * @param perdata
     * @return
     */
    private Map<String, String> toKVs(String perdata) {
        Matcher matcher = pattern.matcher(perdata);
        Map<String, String> result = new HashMap<String, String>();
        while (matcher.find()) {
            String key = matcher.group(1).trim();
            String vs = matcher.group(2).trim();
            String[] allvs = vs.split(";");
            String cv = allvs[0];
            cv = cv.replaceAll("[^0-9\\.]", "");
            result.put(key, cv);
        }
        return result;
    }

    public static PerDataUtils getInstance(){
        return instance;
    }

    public Map<String, String> getPerData(String data) {
        String[] perData = data.trim().split("\\|");
        if (perData.length >= 2) {
            String per = perData[1];
            return toKVs(per + " ");
        }
        return null;
    }
}
